package com.group3.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;

import com.alibaba.fastjson2.JSON;
import com.group3.common.result.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class SentinelExceptionHandlerPage implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        ApiResponse responseData = null;
        if (e instanceof FlowException) {
            responseData = new ApiResponse(444, "请求被限流了",  e.getRule());
             log.error("请求被限流了:{}",e.getMessage());

        } else if (e instanceof DegradeException) {
            responseData = new ApiResponse(555, "请求被熔断了",  e.getRule());
            log.error("请求被熔断了:{}",e.getMessage());
        } else if (e instanceof ParamFlowException) {
            responseData = new ApiResponse(666, "热点参数限流",  e.getRule());
            log.error("热点参数限流:{}",e.getMessage());
        } else if (e instanceof AuthorityException) {
            responseData = new ApiResponse(777, "请求没有权限",  e.getRule());
            log.error("请求没有权限:{}",e.getMessage());
        } else if (e instanceof SystemBlockException) {
            responseData = new ApiResponse(888, "请求负载异常",  e.getRule());
            log.error("请求负载异常:{}",e.getMessage());
        }
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().println(JSON.toJSONString(responseData));
    }
}


